import { Component, OnInit } from '@angular/core';
import { PickerController } from '@ionic/angular';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { Login, Logout, SwitchAutoPlaying, UpdateChapterNo, UpdateWaitTime } from './../store/actions/app.action';

import { ToastService } from 'src/app/service/toast.service';
import { AppState } from '../store/state/app.state';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {
  @Select(AppState.getIsLogin)
  public isLogin: Observable<boolean>;

  @Select(AppState.getUserName)
  public userName: Observable<string>;

  @Select(AppState.getTotalQuantity)
  public totalQuantity: Observable<number>;

  @Select(AppState.getAutoPlaying)
  public autoPlaying: Observable<boolean>;

  @Select(AppState.getWaitTime)
  public currentWaitTime: Observable<number>;

  @Select(AppState.getCurrentChapterNo)
  public currentChapterNo: Observable<number>;

  @Select(AppState.getCurrentSequenceNo)
  public currentSequenceNo: Observable<number>;

  public email: string;
  public password: string;

  private totalQty: number;
  private chapterNo: number;
  constructor(private toastService: ToastService, private store: Store, private pickerCtrl: PickerController) {}

  public ngOnInit(): void {
    this.totalQuantity.subscribe((n) => {
      this.totalQty = n;
    });
    this.currentChapterNo.subscribe((n) => {
      this.chapterNo = n;
    });
  }
  public login() {
    const email = this.email;
    const password = this.password;

    this.store.dispatch(new Login({ email, password })).subscribe((n) => {
      this.toastService.showInfo('登录成功.');
    });
  }

  public logout() {
    this.store.dispatch(Logout).subscribe((n) => {});
  }

  public switchAutoPlaying(event: any) {
    this.store.dispatch(new SwitchAutoPlaying(event.detail.checked));
  }
  public onIonChange(event: any) {
    this.store.dispatch(new UpdateWaitTime(event.detail.value));
  }
  public pinFormatter(value: number) {
    return `${value}`;
  }
  public async openPicker() {
    const options = [];

    for (let i = 0; i < this.totalQty / 50; i++) {
      options.push({
        text: (i + 1).toString(),
        value: i + 1,
      });
    }

    const picker = await this.pickerCtrl.create({
      columns: [
        {
          name: 'chapterNos',
          options,
          selectedIndex: this.chapterNo - 1,
        },
      ],
      buttons: [
        {
          text: '取消',
          role: '取消',
        },
        {
          text: '确认',
          handler: (data) => {
            this.store.dispatch(new UpdateChapterNo(data.chapterNos.value));
          },
        },
      ],
    });

    await picker.present();
  }
}
